import user from '@/modules/user.api.js';
import demo from '@/modules/demo.api.js';
let token = '';
let timer = null;
const install = (Vue, vm) => {
  _bindVm(vm, demo, user)
  // 将各个定义的接口名称，统一放进对象挂载到vm.$u.api(因为vm就是this，也即this.$u.api)下
  vm.$u.api = {
    demo,
    user
  }
  let baseUrl = ''
  // #ifdef MP-WEIXIN
  baseUrl = process.env.VUE_APP_PROXY_URL
  // #endif
  // #ifdef H5
  baseUrl = process.env.VUE_APP_BASE_API
  // #endif
  Vue.prototype.$u.http.setConfig(config => {
    config.baseURL = baseUrl
    return config
  })

  // 请求拦截，配置Token等参数
  Vue.prototype.$u.http.interceptors.request.use(config => {
    console.log(config);
    config.data = config.data || {}
    token = uni.getStorageSync('access_token');
    config.header['Authorization'] = token;
    return config
  }, config => { // 可使用async await 做异步操作
    return Promise.reject(config)
  })

  // 响应拦截，判断状态码是否通过
  Vue.prototype.$u.http.interceptors.response.use((response) => {
    const data = response.data
    if (data.code === 401) {
      vm.$u.toast('登陆状态已过期！');
      if (!timer) {
        timer = setTimeout(() => {
          token = '';
          uni.removeStorageSync('access_token');
          uni.reLaunch({ url: '/pages/login/login' });
          clearTimeout(timer);
          timer = null;
        }, 1000);
        return Promise.reject(new Error(data.msg));
      }
    } else if (data.code === 200) { // 此处可扩展接口调用成功的状态码
      return data
    } else {
      vm.$u.toast(data.msg);
      return Promise.reject(new Error(data.msg))
    }
  }, (response) => {
    vm.$u.toast('网络异常，请稍后再试')
    return Promise.reject(new Error(response.errMsg))
  })
}
function _bindVm(vm, ...args) {
  Array.isArray(args) && args.forEach(target => {
    for (const fn in target) {
      if (Object.hasOwnProperty.call(target, fn)) {
        if (typeof target[fn] === 'function') {
          target[fn] = target[fn].bind(vm)
        }
      }
    }
  })
}
export default {
  install
}
